package com.ybu.service.impl;

import com.ybu.common.ServiceCode;
import com.ybu.common.ServiceException;
import com.ybu.mapper.AddFavoriteMapper;
import com.ybu.mapper.DeletFavoriteMapper;
import com.ybu.mapper.ProductMapper;
import com.ybu.pojo.entity.Favorite;
import com.ybu.pojo.entity.Product;
import com.ybu.pojo.vo.UserLoginVO;
import com.ybu.service.DeletFavoriteService;
import org.springframework.stereotype.Service;

@Service
public class DeletFavoriteServiceImpl implements DeletFavoriteService {
    private   ProductMapper productMapper;
    private DeletFavoriteMapper deletFavoriteMapper;
    private  AddFavoriteMapper addFavoriteMapper;
    @Override
    public void delet(Integer productId, UserLoginVO userLoginVO) {

        Product product = productMapper.getById(productId);
        if(product==null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该商品不存在");
        }
        Favorite Favorite = addFavoriteMapper.findByProductIdAndUserId(productId, userLoginVO.getId());
        if (Favorite == null) {
            throw new ServiceException(ServiceCode.ERR_FORBIDDEN,"商品未被收藏，不能取消收藏");
        } else{
            Favorite favorite = new Favorite();
            favorite.setProductId(productId);
            favorite.setUserId(userLoginVO.getId());
            int result = deletFavoriteMapper.deletFavorite(favorite);
            // 根据受影响的行数判断操作是否成功
            if(result != 1){
                throw  new ServiceException(ServiceCode.ERR_DELETE_FAILED,"取消收藏失败");
            }
        }
    }
}

